package com.drakulo.hi.logic.actions;

import java.util.ArrayList;
import java.util.List;

import com.dk.hi.core.exceptions.HIException;
import com.drakulo.hi.logic.actions.conditions.Condition;

/**
 * <b>Conditionnal action</b>
 * <p>
 * A condition surrounding a list of actions with this pattern :<br>
 * <code>IF <i>conditions</i> THEN <i>thenActions</i> ELSE <i>elseActions</i></code>
 * </p>
 * <p>
 * If the <i>conditions</i> are met, the <i>thenActions</i> are executed.
 * Otherwise, <i>elseActions</i> are executed
 * </p>
 */
public class ConditionalAction implements Action {
	/**
	 * Condition list
	 */
	private List<Condition> conditions;

	/**
	 * Actions to execute if contitions are met
	 */
	private List<Action> thenActions;

	/**
	 * Action to execute if condition aren't met. This list may be null for a
	 * simple "if" condition.
	 */
	private List<Action> elseActions;

	/**
	 * Constructor
	 */
	public ConditionalAction() {
		this.conditions = new ArrayList<Condition>();
		this.thenActions = new ArrayList<Action>();
		this.elseActions = new ArrayList<Action>();
	}

	/**
	 * Add a condition
	 * 
	 * @param c
	 *            - The condition
	 */
	public void addCondition(Condition c) {
		this.conditions.add(c);
	}

	/**
	 * Add an action to the "else" list
	 * 
	 * 
	 * @param a
	 *            - l'action
	 */
	public void addElseAction(Action a) {
		this.elseActions.add(a);
	}

	/**
	 * Add an action to the "then" list
	 * 
	 * @param a
	 *            - l'action
	 */
	public void addThenAction(Action a) {
		this.thenActions.add(a);
	}

	@Override
	public void run() throws HIException {
		boolean conditionsOk = true;

		// Verify conditions
		for (Condition c : this.conditions) {
			if (c.test() == false) {
				// Oops! One condition is not met
				conditionsOk = false;
				break;
			}
		}

		if (conditionsOk) {
			for (Action a : this.thenActions) {
				a.run();
			}
		} else {
			for (Action a : this.elseActions) {
				a.run();
			}
		}
	}

}
